let isIframe = window.self !== window.top;

function loginSuccessAlert(user) {
    parent.layer.alert(`${user.username}，登录成功`, {
        time: 3 * 1000,
        success: function(layero, index){
            let timeNum = this.time/1000;
            let setText = function(start){
                parent.layer.title('<span class="layui-font-red">'+ (start ? timeNum : --timeNum) + '</span> 秒后自动刷新', index);
            };
            setText(!0);
            this.timer = setInterval(setText, 1000);
            if(timeNum <= 0) clearInterval(this.timer);
        },
        end: function(){
            clearInterval(this.timer);
            // 登陆成功，刷新父页面
            parent.location.reload();
        }
    });
}

async function loginPost(data, url = "/api/auth/login") {
    try {
        // 创建 FormData 对象
        let body = new FormData();
        for (let key in data) {
            body.append(key, data[key]);
        }

        // 使用 fetch 发送 POST 请求
        const response = await fetch(url, {
            method: 'POST',
            body: body
        });

        // 检查响应状态码
        if (!response.ok && (response.status < 400 && response.status >= 500)) {
            parent.layui.layer.alert(`请求结果出错！<br />状态码：${response.status}`);
            throw new Error(`HTTP error! status: ${response.status}`);
            return false;
        }

        // 解析返回的 JSON 数据
        const dataResponse = await response.json();

        // 检查响应状态码
        if (!response.ok) {
            parent.layui.layer.alert(dataResponse.msg);
            return false;
        }

        loginSuccessAlert(dataResponse);
        return true;
    } catch (error) {
        parent.layui.layer.alert(`请求网络出错！<br />${error}`);
        console.error(error);
        return false;
    }
}

function loginFunction(data) {
    const field = data.field; // 获取表单字段值
    loginPost(field).then(r => {});
    return false; // 阻止默认 form 跳转
}
function initLayui() {
    layui.form.on('submit(login)', loginFunction);
        // 事件
    layui.util.on('lay-on', {
        'forget-register': function(){
            parent.layer.alert('请联系网站管理员！');
        }
    });
}


document.addEventListener('DOMContentLoaded', (event) => {
    layui.use(initLayui);
});